package vip.xianz.jobmanager.aop;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import vip.xianz.jobmanager.data.vo.ResultBean;
import vip.xianz.jobmanager.exception.CheckException;

/**
 * 处理和包装异常
 * @author submitX
 * @date 2019-5-5 07:45:24
 */
public class ControllerAOP  {
	private static final Logger logger = LoggerFactory.getLogger(ControllerAOP.class);
	
	/**
	 * 处理controller方法并统计执行时间
	 */
	public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
		Instant start = Instant.now();
		ResultBean<?> result = null;
		try {
			result = (ResultBean<?>) pjp.proceed();
			logger.info(pjp.getSignature() + " use time:" + ChronoUnit.MILLIS.between(start, Instant.now()));
		} catch (Throwable e) {
			result = handlerException(pjp, e);
		}
		return result;
	}

	/**
	 * 对异常的处理
	 */
	private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		ResultBean<?> result = new ResultBean<>();
		if (e instanceof CheckException) {
			// 已知异常
			result.setMsg(e.getLocalizedMessage());
			result.setCode(ResultBean.FAIL);
		} else {
			// 未知异常
			logger.error(pjp.getSignature() + " error " + e);
			result.setMsg(e.toString());
			result.setCode(ResultBean.FAIL);
		}
		return result;
	}
}
